import React from 'react';
import {Form, Row, Col, Button, DatePicker, message ,Divider,Select} from 'antd';
import StatisticsBox from '../../components/box/statistics';
import {sessionManager} from '../../utils/sessionStorage';
import AdjustHis from './AdjustHis';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import axios from 'axios';
import moment from 'moment';
import { getYear } from '../../utils/Array';
import qs from 'qs';

const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
class ledgerMonthBill extends React.Component {
	constructor(props) {
		super(props);
		this.common = this.props.intl.messages.common;
		this.columns = [
			{
				title: '结算月份',
				width: '150',
				dataIndex:'ym',
				key: 'ym'
			},
			{
				title: '电量（KWH）',
				dataIndex: 'settlementPower',
				key: 'settlementPower',
				width: '150',
			},
			{
				title: '电费（元）',
				dataIndex: 'settlementElectric',
				key: 'settlementElectric',
				width: '150',
			},
			{
				title: '服务费（元）',
				dataIndex: 'settlementService',
				key: 'settlementService',
				width: '150',
			},
			{
				title: '结算金额（元）',
				dataIndex: 'settlementMoney',
				key: 'settlementMoney',
				width: '150',
			},
			{
				title: '状态',
				dataIndex: 'status',
				key: 'status',
				width: '150',
				render: (text) => (
					text.status === 0 || text==='0' ? '结算中' : '结算完成'
				)
			},
			{
				title: '营销成本（元）',
				key:'marketingMoney',
				width: '150',
				render: (text,record) => {
					if(text.marketingMoney > 0){
						return <a onClick={() => this.goLink(text,record, 'discountDetail')}>{text.marketingMoney}</a>
					}else{
						return text.marketingMoney
					}

				}
			},
			{
				title: '调整金额（元）',
				dataIndex: 'adjustmentMoney',
				key: 'adjustmentMoney',
				width: '150',
			},
			{
				title: '实际金额（元）',
				dataIndex: 'money',
				key: 'money',
				width: '150',
			},
			{
				title: this.common.operation,
				key: 'action',
				fixed: 'right',
				width: 100,
				render: (text, record) => (
					<span>
                        <a onClick={() => this.goLink(text, record, 'ledgerMonthDetail')}>账单详情</a>
                    </span>
				)
			}
		];
		this.state = {
			params:{
				year:moment().format('YYYY')
			},
			selectTime: moment().format('YYYY.MM.DD 23:59:59'),
			summary: [],
			visible: false,
			refresh:0
		}
	}

	componentWillMount() {
		axios.get('/api/settlement/billSplit/myBillOrderTotal').then(res=>{
			if(res&&res.code=='200'){
				const billData=res.data;
				this.setState({
					summary: [
						{
							num: billData.settlementPower,
							desc: '总分账电量（KWH）',
							// style:{width:400}
						},
						{
							num: billData.settlementElectric,
							desc: '总基本电费（元）'
						},
						{
							num: billData.settlementService,
							desc: '总服务费（元）'
						},
						{
							num: billData.settlementMoney,
							desc: '总费用（元）'
						}
					]
				});
			}
		})
		// this.getTotal()
	}

	handleCancel = () => {
		this.setState({
			visible: false,
		})
	};

	goLink = (text, record, link) => {
		sessionManager.set('discountInfo',text);
		this.props.history.push({pathname: `/finance/${link}`,state: {ym: text.ym}});
	};
	goBill = () => {
		sessionManager.set('BillInfo', this.state.totalData);
		this.props.history.push({pathname: '/finance/BillDetails'});
	};

	// submitSettle = () => {
	// 	axios.post('/api/settlement/unSettled/submitSettle', {...{splitTime: this.state.totalData.splitTime}}).then(res => {
	// 		if (res && res.code == 200) {
	// 			if (res.data > 0) {
	// 				message.success('提交结算操作成功')
	// 			} else {
	// 				message.error('提交结算操作失败')
	// 			}
	// 		}
	// 	})
	// };

	transFormNull=(data)=>{
		for(let i=0;i<data.length;i++){
			if(!data[i].id){
				data[i].id=i
			}
		}
		return data
	}

	transformData=(data)=>{
		// let newData = this.transFormNull(data.list);
		// this.setState({
		// 	lastMoney:data.lastMoney,
		// 	lastPower:data.lastPower,
		// 	summary: [
		// 		{
		// 			num: data.settlementPower,
		// 			desc: '初次结算电量',
		// 			// style:{width:400}
		// 		},
		// 		{
		// 			num: data.settlementMoney,
		// 			desc: '初次结算金额'
		// 		},
		// 		{
		// 			num: [],
		// 			actions: () => {
		// 				return (
		// 					<Button type="primary" onClick={this.showModal}>添加调整单</Button>
		// 				)
		// 			}
		// 		}
		// 	]
		// });
		return data;
	};

	endTimeLess = (rule, value, callback) => {

		if (value.isAfter(moment().format('YYYY.MM.DD'))) {
			callback(`请选择${moment().format('MM月DD日')}之前的时间`);
		} else {
			callback();
		}
	}

	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (!!err) {
				return;
			}
			console.log(values);
			this.setState(Object.assign(this.state.params,values));
			this.setState({
				refresh:this.state.refresh+1
			})
		});
	};

	render() {
		const token=JSON.parse(sessionStorage.getItem("token")||{}).token;
		let locale=sessionManager.get('locale');
		let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
		console.log('exportQs',exportQs);
		const {getFieldDecorator} = this.props.form;
		const dateFormat = 'YYYY.MM.DD';
		return (
			<div>
				{/*<form form={this.props.form} className="SC-form">
					<Row gutter={24} type="flex">
						<Col span={3}>
							<FormItem
							>
								{getFieldDecorator('year',{
									initialValue:this.state.params.year
								})(
									<Select placeholder={'年份'}>
										{getYear().map((k, i) => {
											return <Option value={k} key={i}>{k}</Option>
										})}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col>
							<FormItem>
								<Button type="primary" htmlType="submit"
										onClick={this.handleSubmit} className="ant-btn-84">{this.common.search}</Button>
								<a href={`${axios.defaults.baseURL}/api/settlement/settled/monthlyBill/export?${exportQs}`}>
									<Button type="primary">{this.common.exportStatement}</Button>
								</a>
							</FormItem>
						</Col>
					</Row>
				</form>*/}
				<StatisticsBox params={this.state.summary}/>
				<Grid url="api/settlement/billSplit/myBillOrderMonthList" columns={this.columns} refresh={this.state.refresh} transformData={this.transformData} />
				{/*<AdjustHis visible={this.state.visible} handleCancel={this.handleCancel}/>*/}
			</div>
		)
	}
}

ledgerMonthBill = createForm()(ledgerMonthBill);
export default injectIntl(ledgerMonthBill)
